package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class ReFlushInterceptor implements HandlerInterceptor {
    private RedisTemplate redisTemplate;

    /**
     * 因为该自定义拦截器没有被spring容器直接管理，所以只能通过构造器的方式注入依赖
     * @param redisTemplate
     */
    public ReFlushInterceptor(RedisTemplate redisTemplate){
        this.redisTemplate=redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截请求，判断session中的user是否为空
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)){
            //如果token为空那么直接放行，过关斩将
            return true;
        }
        Map entries = redisTemplate.opsForHash().entries(token);
        if (entries.isEmpty()){
            return true;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), true);
        //将对象保存到ThreadLocal
        UserHolder.saveUser(userDTO);
        //更新过期时间
        redisTemplate.expire(token,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
